package cn.ratel.route;

import cn.ratel.kit.JsonKit;
import cn.ratel.tool.TypeConverter;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;

class ActionParam {
	private String paramName;
	private Class paramType;
	private ActionParamProvider.Injector injector;

	ActionParam(Parameter parameter) {
		this.paramType = parameter.getType();
		this.paramName = parameter.getName();
		this.injector = ActionParamProvider.getInjector(paramType);
	}

	Object getParamValue() {
		HttpServletRequest request = ContextHolder.getRequest().get();
		HttpServletResponse response = ContextHolder.getResponse().get();
		String paramValue = request.getParameter(paramName);
		// Injector
		if (injector != null) {
			return injector.inject(request, response, paramName);
		}
		// Model
		else if (ContextHolder.getModelAttrMap().get().containsKey(paramName)) {
			String jsonStr = JSON.toJSONString(ContextHolder.getModelAttrMap().get().get(paramName));
			return JSON.parseObject(jsonStr, paramType);
		}
		// JSON
		else if (paramValue != null && (paramValue.startsWith("{") || paramValue.startsWith("[") || paramValue.startsWith("\""))) {
			return JsonKit.toObject(paramValue, paramType);
		} else {
			// Req.getParameter
			return TypeConverter.convert(paramType, paramValue);
		}
	}

	@Override
	public String toString() {
		return "{" +
				"paramType=" + paramType +
				", paramName='" + paramName + '\'' +
				'}';
	}
}
